<template>
  <div class="membership-container">
    <h1 class="page-title">会员与充值中心</h1>
    
    <div v-if="!currentUser" class="not-logged-in">
      <p>请先登录后再进行充值或购买会员</p>
      <router-link to="/login" class="login-link">去登录</router-link>
    </div>
    
    <div v-else class="membership-content">
      <!-- 用户信息卡片 -->
      <div class="user-info-card">
        <div class="user-details">
          <h2>欢迎，{{ currentUser.username }}</h2>
          <p class="user-email">{{ currentUser.email }}</p>
        </div>
        <div class="user-stats">
          <div class="stat-item">
            <span class="stat-label">当前金币</span>
            <span class="stat-value coins">{{ currentUser.balance || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">会员状态</span>
            <span class="stat-value" :class="{ 'member-active': membershipStatus.isMember }">
              {{ membershipStatus.isMember ? '已激活' : '未激活' }}
            </span>
          </div>
          <div class="stat-item" v-if="membershipStatus.isMember">
            <span class="stat-label">到期时间</span>
            <span class="stat-value">{{ formatDate(membershipStatus.memberExpiry) }}</span>
          </div>
          <div class="stat-item" v-if="membershipStatus.isMember">
            <span class="stat-label">剩余天数</span>
            <span class="stat-value days-remaining">{{ membershipStatus.daysRemaining }}天</span>
          </div>
        </div>
      </div>

      <div class="tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.id"
          :class="['tab-button', { active: activeTab === tab.id }]"
          @click="activeTab = tab.id"
        >
          {{ tab.name }}
        </button>
      </div>

      <!-- 充值面板 -->
      <div v-if="activeTab === 'recharge'" class="tab-content recharge-panel">
        <h3>金币充值</h3>
        <p class="panel-description">充值金币可以用于购买会员和其他增值服务</p>
        
        <div class="recharge-options">
          <div 
            v-for="plan in RECHARGE_PLANS" 
            :key="plan.amount"
            :class="['recharge-option', { selected: selectedAmount === plan.amount }]"
            @click="selectedAmount = plan.amount"
          >
            <div class="plan-amount">¥{{ plan.amount }}</div>
            <div class="plan-coins">
              {{ plan.coins }}金币
              <span v-if="plan.coins > plan.amount * 10" class="bonus">
                (额外赠送{{ plan.coins - plan.amount * 10 }}金币)
              </span>
            </div>
          </div>
        </div>
        
        <div class="action-buttons">
          <button 
            class="recharge-button" 
            @click="handleRecharge"
            :disabled="!selectedAmount || isLoading"
          >
            {{ isLoading ? '处理中...' : '立即充值' }}
          </button>
        </div>
      </div>

      <!-- 会员购买面板 -->
      <div v-if="activeTab === 'membership'" class="tab-content membership-panel">
        <h3>会员购买</h3>
        <p class="panel-description">开通会员享受专属特权，提升游戏体验</p>
        
        <div class="membership-benefits">
          <h4>会员特权</h4>
          <ul>
            <li>✓ 独家游戏攻略和战术指导</li>
            <li>✓ 高级地图标记和物资分布分析</li>
            <li>✓ 武器数据分析和推荐配置</li>
            <li>✓ 无广告体验</li>
            <li>✓ 优先体验新功能</li>
            <li>✓ 会员专属活动</li>
          </ul>
        </div>
        
        <div class="membership-options">
          <div 
            v-for="(plan, key) in MEMBERSHIP_PLANS" 
            :key="plan.id"
            :class="['membership-option', { selected: selectedPlan === key }]"
            @click="selectedPlan = key"
          >
            <div class="plan-header">
              <h4>{{ plan.name }}</h4>
              <div class="plan-price">{{ plan.price }}金币</div>
            </div>
            <div class="plan-duration">{{ plan.duration }}天</div>
            <div class="plan-description">{{ plan.description }}</div>
          </div>
        </div>
        
        <div class="action-buttons">
          <button 
            class="purchase-button" 
            @click="handlePurchaseMembership"
            :disabled="!selectedPlan || isLoading || (currentUser.balance || 0) < MEMBERSHIP_PLANS[selectedPlan]?.price"
          >
            {{ isLoading ? '处理中...' : '立即购买' }}
          </button>
          <p v-if="(currentUser.balance || 0) < MEMBERSHIP_PLANS[selectedPlan]?.price" class="balance-warning">
            金币余额不足，请先充值
          </p>
        </div>
      </div>

      <!-- 交易记录面板 -->
      <div v-if="activeTab === 'transactions'" class="tab-content transactions-panel">
        <h3>交易记录</h3>
        
        <div v-if="transactions.length === 0" class="no-transactions">
          暂无交易记录
        </div>
        
        <div v-else class="transactions-list">
          <div 
            v-for="transaction in transactions" 
            :key="transaction.id"
            class="transaction-item"
          >
            <div class="transaction-date">{{ formatDate(transaction.timestamp) }}</div>
            <div class="transaction-details">
              <div class="transaction-type">
                {{ transaction.type === 'recharge' ? '金币充值' : '会员购买' }}
              </div>
              <div class="transaction-amount">¥{{ transaction.amount }}</div>
            </div>
            <div class="transaction-coins" :class="{ positive: transaction.coinsChange > 0 }">
              {{ transaction.coinsChange > 0 ? '+' : '' }}{{ transaction.coinsChange }}金币
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 成功提示 -->
    <div v-if="showSuccess" class="success-message">
      {{ successMessage }}
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { authService } from '../services/auth.js'
import { membershipService, MEMBERSHIP_PLANS, RECHARGE_PLANS } from '../services/membership.js'

export default {
  name: 'MembershipView',
  setup() {
    const router = useRouter()
    const currentUser = ref(null)
    const membershipStatus = ref({ isMember: false, memberExpiry: null, daysRemaining: 0 })
    const activeTab = ref('recharge')
    const selectedAmount = ref(null)
    const selectedPlan = ref('MONTHLY')
    const isLoading = ref(false)
    const showSuccess = ref(false)
    const successMessage = ref('')
    const transactions = ref([])

    const tabs = [
      { id: 'recharge', name: '金币充值' },
      { id: 'membership', name: '会员购买' },
      { id: 'transactions', name: '交易记录' }
    ]

    const loadUserInfo = () => {
      const user = authService.getCurrentUser()
      if (user) {
        currentUser.value = user
        membershipStatus.value = membershipService.getCurrentMembershipStatus()
        transactions.value = membershipService.getUserTransactions(user.id)
      }
    }

    const handleRecharge = async () => {
      if (!selectedAmount.value) return
      
      isLoading.value = true
      try {
        const result = await membershipService.recharge(currentUser.value.id, selectedAmount.value)
        successMessage.value = `充值成功！获得${result.coinsAdded}金币`
        showSuccess.value = true
        
        // 重新加载用户信息
        loadUserInfo()
        
        // 3秒后隐藏提示
        setTimeout(() => {
          showSuccess.value = false
        }, 3000)
      } catch (error) {
        alert(`充值失败: ${error.message}`)
      } finally {
        isLoading.value = false
      }
    }

    const handlePurchaseMembership = async () => {
      if (!selectedPlan.value) return
      
      isLoading.value = true
      try {
        const result = await membershipService.purchaseMembership(currentUser.value.id, selectedPlan.value)
        successMessage.value = `会员购买成功！有效期至${formatDate(result.newExpiryDate)}`
        showSuccess.value = true
        
        // 重新加载用户信息
        loadUserInfo()
        
        // 3秒后隐藏提示
        setTimeout(() => {
          showSuccess.value = false
        }, 3000)
      } catch (error) {
        alert(`购买失败: ${error.message}`)
      } finally {
        isLoading.value = false
      }
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    onMounted(() => {
      loadUserInfo()
    })

    return {
      currentUser,
      membershipStatus,
      activeTab,
      tabs,
      selectedAmount,
      selectedPlan,
      isLoading,
      showSuccess,
      successMessage,
      transactions,
      MEMBERSHIP_PLANS,
      RECHARGE_PLANS,
      handleRecharge,
      handlePurchaseMembership,
      formatDate
    }
  }
}
</script>

<style scoped>
.membership-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
}

.not-logged-in {
  text-align: center;
  padding: 50px 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.login-link {
  display: inline-block;
  margin-top: 20px;
  padding: 10px 30px;
  background: #3498db;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background 0.3s;
}

.login-link:hover {
  background: #2980b9;
}

.user-info-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 25px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.user-details h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.user-email {
  opacity: 0.9;
  margin: 0;
}

.user-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 120px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
}

.stat-value.coins {
  color: #ffd700;
}

.stat-value.member-active {
  color: #4ade80;
}

.stat-value.days-remaining {
  color: #facc15;
}

.tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  border-bottom: 2px solid #e5e7eb;
}

.tab-button {
  padding: 12px 24px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 16px;
  color: #6b7280;
  border-bottom: 3px solid transparent;
  transition: all 0.3s;
}

.tab-button.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
  font-weight: bold;
}

.tab-button:hover:not(.active) {
  color: #374151;
}

.tab-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.panel-description {
  color: #6b7280;
  margin-bottom: 30px;
}

.recharge-options {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.recharge-option {
  padding: 20px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
}

.recharge-option:hover {
  border-color: #3b82f6;
  transform: translateY(-2px);
}

.recharge-option.selected {
  border-color: #3b82f6;
  background: #eff6ff;
}

.plan-amount {
  font-size: 24px;
  font-weight: bold;
  color: #3b82f6;
  margin-bottom: 10px;
}

.plan-coins {
  color: #6b7280;
}

.plan-coins .bonus {
  color: #f59e0b;
  font-size: 14px;
}

.membership-options {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.membership-option {
  padding: 25px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.membership-option:hover {
  border-color: #8b5cf6;
  transform: translateY(-2px);
}

.membership-option.selected {
  border-color: #8b5cf6;
  background: #f5f3ff;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.plan-header h4 {
  margin: 0;
  font-size: 20px;
  color: #4b5563;
}

.plan-price {
  font-size: 22px;
  font-weight: bold;
  color: #8b5cf6;
}

.plan-duration {
  font-size: 16px;
  color: #f59e0b;
  margin-bottom: 10px;
}

.plan-description {
  color: #6b7280;
  font-size: 14px;
}

.membership-benefits {
  background: #f8fafc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.membership-benefits h4 {
  margin: 0 0 15px 0;
  color: #374151;
}

.membership-benefits ul {
  margin: 0;
  padding-left: 20px;
}

.membership-benefits li {
  margin-bottom: 8px;
  color: #6b7280;
}

.action-buttons {
  text-align: center;
}

.recharge-button,
.purchase-button {
  padding: 12px 40px;
  font-size: 16px;
  font-weight: bold;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s;
}

.recharge-button {
  background: #10b981;
  color: white;
}

.recharge-button:hover:not(:disabled) {
  background: #059669;
}

.purchase-button {
  background: #8b5cf6;
  color: white;
}

.purchase-button:hover:not(:disabled) {
  background: #7c3aed;
}

.recharge-button:disabled,
.purchase-button:disabled {
  background: #9ca3af;
  cursor: not-allowed;
}

.balance-warning {
  color: #ef4444;
  margin-top: 15px;
}

.transactions-list {
  max-height: 500px;
  overflow-y: auto;
}

.transaction-item {
  padding: 15px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.transaction-item:last-child {
  border-bottom: none;
}

.transaction-date {
  color: #6b7280;
  font-size: 14px;
  min-width: 150px;
}

.transaction-details {
  flex: 1;
  margin: 0 20px;
}

.transaction-type {
  font-weight: 500;
  color: #374151;
}

.transaction-amount {
  color: #6b7280;
  font-size: 14px;
  margin-top: 4px;
}

.transaction-coins {
  font-weight: bold;
  color: #ef4444;
  min-width: 100px;
  text-align: right;
}

.transaction-coins.positive {
  color: #10b981;
}

.no-transactions {
  text-align: center;
  padding: 50px;
  color: #9ca3af;
}

.success-message {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #10b981;
  color: white;
  padding: 15px 25px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .user-stats {
    flex-direction: column;
    align-items: center;
  }
  
  .stat-item {
    min-width: auto;
  }
  
  .tabs {
    flex-wrap: wrap;
  }
  
  .tab-button {
    flex: 1;
    min-width: 120px;
  }
  
  .recharge-options,
  .membership-options {
    grid-template-columns: 1fr;
  }
  
  .transaction-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .transaction-coins {
    text-align: left;
    min-width: auto;
  }
}
</style>